import jwt from 'jsonwebtoken';
import { AuthPayloadType } from '~/types/user';

const unauthorizedTokenErrorCreater = (msg: string) => createError({ statusCode: 401, statusMessage: msg });

const invalidTokens: string[] = [];

export default defineEventHandler(async event => {
    const { path } = event;
    if (path.startsWith('/api') && !path.match(/^\/api\/(signin|signup)/)) {
        const token = getRequestHeader(event, 'Authorization')?.split(' ')[1];
        // 无token、已注销token
        if (!token || invalidTokens.includes(token)) throw unauthorizedTokenErrorCreater('Unauthorized Access');
        try {
            const auth = jwt.verify(token, process.env.JWT_KEY as string) as AuthPayloadType;
            if (path === '/api/logout') {
                // 注销逻辑
                invalidTokens.push(token);
            }
            else {
                event.context.auth = auth;
                event.context.auth.token = token;
            }
        }
        catch (e) {
            if (e instanceof jwt.JsonWebTokenError || e instanceof jwt.TokenExpiredError) throw unauthorizedTokenErrorCreater(e.message);
        }
    }
});